package com.ruoyi.service.impl;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.domain.CarBorder;
import com.ruoyi.domain.CarCorder;
import com.ruoyi.domain.MobilOrder;
import com.ruoyi.domain.MobilOrderDetails;
import com.ruoyi.mapper.CarBorderMapper;
import com.ruoyi.mapper.MobileCarCorderMapper;
import com.ruoyi.mapper.MobileCarOrderDetailsMapper;

import com.ruoyi.service.IMobilOrderService;
import com.ruoyi.service.IMobileUserCouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 手机端订单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-20
 */
@Service
public class MobilOrderServiceImpl implements IMobilOrderService {

    
    @Autowired
    private MobileCarCorderMapper mobileCarCorderMapper;
    
    @Autowired
    private CarBorderMapper carBorderMapper;
    
    @Autowired
    private MobileCarOrderDetailsMapper mobileCarOrderDetailsMapper;
    
    @Autowired
    private IMobileUserCouponService mobileUserCouponService;

    /**
     * 查询订单列表
     *
     * @param mobilOrder 订单
     * @return 订单集合
     */
    @Override
    public List<MobilOrder> selectMobilOrderList(MobilOrder mobilOrder) {
        // 使用 CarCorder 数据转换为 MobilOrder
        List<CarCorder> carCorders = mobileCarCorderMapper.selectCarCordersByUserId(mobilOrder.getUserId());
        List<MobilOrder> mobilOrders = new ArrayList<>();
        for (CarCorder carCorder : carCorders) {
            MobilOrder order = convertCarCorderToMobilOrder(carCorder);
            mobilOrders.add(order);
        }
        return mobilOrders;
    }

    /**
     * 根据用户ID查询订单列表
     *
     * @param userId 用户ID
     * @return 订单集合
     */
    @Override
    public List<MobilOrder> selectOrdersByUserId(Integer userId) {
        List<CarCorder> carCorders = mobileCarCorderMapper.selectCarCordersByUserId(userId);
        List<MobilOrder> mobilOrders = new ArrayList<>();
        for (CarCorder carCorder : carCorders) {
            MobilOrder order = convertCarCorderToMobilOrder(carCorder);
            mobilOrders.add(order);
        }
        return mobilOrders;
    }

    /**
     * 根据用户ID和订单状态查询订单列表
     *
     * @param userId 用户ID
     * @param orderStatus 订单状态
     * @return 订单集合
     */
    @Override
    public List<MobilOrder> selectOrdersByUserIdAndStatus(Integer userId, Integer orderStatus) {
        // 这里需要添加按状态过滤的逻辑，暂时返回所有订单后过滤
        List<CarCorder> carCorders = mobileCarCorderMapper.selectCarCordersByUserId(userId);
        List<MobilOrder> mobilOrders = new ArrayList<>();
        for (CarCorder carCorder : carCorders) {
            if (carCorder.getOrderStatus().equals(orderStatus)) {
                MobilOrder order = convertCarCorderToMobilOrder(carCorder);
                mobilOrders.add(order);
            }
        }
        return mobilOrders;
    }

    /**
     * 根据订单号查询订单详情
     *
     * @param orderNumber 订单号
     * @return 订单
     */
    @Override
    public MobilOrder selectMobilOrderByNumber(String orderNumber) {
        CarCorder carCorder = mobileCarCorderMapper.selectCarCorderByOrderNumber(orderNumber);
        return carCorder != null ? convertCarCorderToMobilOrder(carCorder) : null;
    }

    /**
     * 根据主键查询订单
     *
     * @param orderId 订单主键
     * @return 订单
     */
    @Override
    public MobilOrder selectMobilOrderById(Integer orderId) {
        CarCorder carCorder = mobileCarCorderMapper.selectCarCorderById(orderId);
        return carCorder != null ? convertCarCorderToMobilOrder(carCorder) : null;
    }

    /**
     * 创建订单
     *
     * @param mobilOrder 订单信息
     * @param serviceIds 服务ID列表
     * @return 结果
     */
    @Override
    @Transactional
    public int createOrder(MobilOrder mobilOrder, List<Integer> serviceIds) {
        // 生成订单号
        String orderNumber = generateOrderNumber();
        mobilOrder.setOrderNumber(orderNumber);
        System.out.println("[ORDER-CREATE] Service层生成的订单号: " + orderNumber);
        System.out.println("[ORDER-CREATE] 设置到mobilOrder对象的订单号: " + mobilOrder.getOrderNumber());
        
        // 生成核销码
        String verificationCode = generateVerificationCode();
        mobilOrder.setVerificationCode(verificationCode);
        
        // 设置订单创建时间和更新时间
        Date now = new Date();
        mobilOrder.setCreateTime(now);
        mobilOrder.setUpdateTime(now);
        
        // 设置默认订单状态为待支付（只有在前端未传递状态时才设置默认值）
        if (mobilOrder.getOrderStatus() == null) {
            mobilOrder.setOrderStatus(0);
            System.out.println("[ORDER-CREATE] Service层使用默认订单状态: 0");
        } else {
            System.out.println("[ORDER-CREATE] Service层使用前端传递的订单状态: " + mobilOrder.getOrderStatus());
        }

        // 1. 插入car_corder表（用户订单表）
        CarCorder carCorder = new CarCorder();
        carCorder.setOrderNumber(orderNumber);
        carCorder.setUserId(mobilOrder.getUserId());
        carCorder.setVehicleId(mobilOrder.getVehicleId());
        carCorder.setStoreId(mobilOrder.getStoreId());
        carCorder.setOrderStatus(mobilOrder.getOrderStatus());
        carCorder.setRepairMode(mobilOrder.getRepairMode());
        carCorder.setAppointTime(mobilOrder.getAppointTime());
        carCorder.setCreateTime(now);
        carCorder.setRemark(mobilOrder.getRemark());
        carCorder.setVerificationCode(verificationCode);
        carCorder.setPayAmount(mobilOrder.getPayAmount());
        carCorder.setUpdateTime(now);
        carCorder.setTypeId(mobilOrder.getTypeId());
        
        int corderResult = mobileCarCorderMapper.insertCarCorder(carCorder);
        
        // 2. 插入car_border表（商家订单表）
        CarBorder carBorder = new CarBorder();
        carBorder.setUserId(mobilOrder.getUserId());
        carBorder.setNumber(orderNumber);
        carBorder.setVerificationCode(verificationCode);
        carBorder.setOrderTime(now);
        carBorder.setReservationTime(mobilOrder.getAppointTime());
        carBorder.setCarId(mobilOrder.getVehicleId());
        carBorder.setCouponId(mobilOrder.getCouponId());
        carBorder.setPrice(mobilOrder.getPayAmount() != null ? mobilOrder.getPayAmount().doubleValue() : 0.0f);
        carBorder.setPayStatus(1); // 设置为已支付
        carBorder.setPayTime(now);
        carBorder.setStatus(mobilOrder.getOrderStatus());
        carBorder.setDeleted(0);
        carBorder.setEvaluate("N");
        carBorder.setMid(mobilOrder.getStoreId());
        
        int borderResult = carBorderMapper.insertCarBorder(carBorder);
        
        // 3. 插入car_order_details表（订单详情表）
        if (corderResult > 0 && serviceIds != null && !serviceIds.isEmpty()) {
            // 使用car_corder的主键作为order_id
            List<MobilOrderDetails> orderDetailsList = new ArrayList<>();
            for (Integer serviceId : serviceIds) {
                MobilOrderDetails orderDetails = new MobilOrderDetails();
                orderDetails.setOrderId(carCorder.getOrderId()); // 使用car_corder的主键
                orderDetails.setServiceId(serviceId);
                orderDetailsList.add(orderDetails);
            }
            mobileCarOrderDetailsMapper.batchInsertOrderDetails(orderDetailsList);
        }
        
        // 4. 如果使用了优惠券，更新优惠券状态为已使用
        if (corderResult > 0 && mobilOrder.getCouponId() != null && mobilOrder.getCouponId() > 0) {
            try {
                // 调用优惠券服务更新状态
                mobileUserCouponService.useCoupon(mobilOrder.getCouponId(), (long) carCorder.getOrderId());
                System.out.println("[ORDER-CREATE] 优惠券状态已更新：优惠券ID=" + mobilOrder.getCouponId() + "，订单ID=" + carCorder.getOrderId());
            } catch (Exception e) {
                System.err.println("更新优惠券状态失败：" + e.getMessage());
                // 可以选择回滚事务或者只记录错误日志
                // 这里选择记录日志但不影响订单创建
            }
        }
        
        // 设置返回的订单ID和订单号到 mobilOrder 对象
        mobilOrder.setOrderId(carCorder.getOrderId());
        mobilOrder.setOrderNumber(orderNumber); // 确保订单号设置到对象中
        System.out.println("[ORDER-CREATE] Service层最终返回前的订单号: " + mobilOrder.getOrderNumber());
        System.out.println("[ORDER-CREATE] Service层最终返回前的订单ID: " + mobilOrder.getOrderId());
        
        return corderResult;
    }

    /**
     * 修改订单
     *
     * @param mobilOrder 订单
     * @return 结果
     */
    @Override
    public int updateMobilOrder(MobilOrder mobilOrder) {
        // 转换为 CarCorder 并更新
        CarCorder carCorder = convertMobilOrderToCarCorder(mobilOrder);
        carCorder.setUpdateTime(DateUtils.getNowDate());
        return mobileCarCorderMapper.updateCarCorder(carCorder);
    }

    /**
     * 支付订单
     *
     * @param orderNumber 订单号
     * @return 结果
     */
    @Override
    public int payOrder(String orderNumber) {
        return mobileCarCorderMapper.updateOrderStatusByNumber(orderNumber, 1, new Date());
    }

    /**
     * 取消订单
     *
     * @param orderId 订单ID
     * @return 结果
     */
    @Override
    public int cancelOrder(Integer orderId) {
        CarCorder carCorder = mobileCarCorderMapper.selectCarCorderById(orderId);
        if (carCorder != null) {
            return mobileCarCorderMapper.updateOrderStatusByNumber(carCorder.getOrderNumber(), 3, new Date());
        }
        return 0;
    }

    /**
     * 完成订单
     *
     * @param orderId 订单ID
     * @return 结果
     */
    @Override
    public int completeOrder(Integer orderId) {
        CarCorder carCorder = mobileCarCorderMapper.selectCarCorderById(orderId);
        if (carCorder != null) {
            return mobileCarCorderMapper.updateOrderStatusByNumber(carCorder.getOrderNumber(), 2, new Date());
        }
        return 0;
    }

    /**
     * 获取订单完整信息（包括订单详情）
     *
     * @param orderNumber 订单号
     * @return 订单完整信息
     */
    @Override
    public MobilOrder getOrderCompleteInfo(String orderNumber) {
        CarCorder carCorder = mobileCarCorderMapper.selectCarCorderByOrderNumber(orderNumber);
        if (carCorder != null) {
            MobilOrder order = convertCarCorderToMobilOrder(carCorder);
            // 查询订单详情
            List<MobilOrderDetails> orderDetails = mobileCarOrderDetailsMapper.selectOrderDetailsByOrderId(carCorder.getOrderId());
            order.setOrderDetails(orderDetails);
            return order;
        }
        return null;
    }

    /**
     * 生成订单号
     */
    private String generateOrderNumber() {
        return "MT" + DateUtils.dateTimeNow("yyyyMMddHHmmssSSS") + (int)(Math.random() * 10000);
    }

    /**
     * 生成核销码
     */
    private String generateVerificationCode() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16).toUpperCase();
    }
    
    /**
     * 将CarCorder转换为MobilOrder
     */
    private MobilOrder convertCarCorderToMobilOrder(CarCorder carCorder) {
        MobilOrder mobilOrder = new MobilOrder();
        mobilOrder.setOrderId(carCorder.getOrderId());
        mobilOrder.setOrderNumber(carCorder.getOrderNumber());
        mobilOrder.setUserId(carCorder.getUserId());
        mobilOrder.setVehicleId(carCorder.getVehicleId());
        mobilOrder.setStoreId(carCorder.getStoreId());
        mobilOrder.setOrderStatus(carCorder.getOrderStatus());
        mobilOrder.setRepairMode(carCorder.getRepairMode());
        mobilOrder.setAppointTime(carCorder.getAppointTime());
        mobilOrder.setCreateTime(carCorder.getCreateTime());
        mobilOrder.setRemark(carCorder.getRemark());
        mobilOrder.setVerificationCode(carCorder.getVerificationCode());
        mobilOrder.setPayAmount(carCorder.getPayAmount());
        mobilOrder.setUpdateTime(carCorder.getUpdateTime());
        mobilOrder.setTypeId(carCorder.getTypeId());
        return mobilOrder;
    }
    
    /**
     * 将MobilOrder转换为CarCorder
     */
    private CarCorder convertMobilOrderToCarCorder(MobilOrder mobilOrder) {
        CarCorder carCorder = new CarCorder();
        carCorder.setOrderId(mobilOrder.getOrderId());
        carCorder.setOrderNumber(mobilOrder.getOrderNumber());
        carCorder.setUserId(mobilOrder.getUserId());
        carCorder.setVehicleId(mobilOrder.getVehicleId());
        carCorder.setStoreId(mobilOrder.getStoreId());
        carCorder.setOrderStatus(mobilOrder.getOrderStatus());
        carCorder.setRepairMode(mobilOrder.getRepairMode());
        carCorder.setAppointTime(mobilOrder.getAppointTime());
        carCorder.setCreateTime(mobilOrder.getCreateTime());
        carCorder.setRemark(mobilOrder.getRemark());
        carCorder.setVerificationCode(mobilOrder.getVerificationCode());
        carCorder.setPayAmount(mobilOrder.getPayAmount());
        carCorder.setUpdateTime(mobilOrder.getUpdateTime());
        carCorder.setTypeId(mobilOrder.getTypeId());
        return carCorder;
    }
}








